<template>
  <div class="action-content">
    <el-form
      :model="addform"
      :rules="rules"
      ref="addform"
      label-width="160px"
      size="small"
    >
      <div class="group">
        <div class="row-title">公告信息</div>
        <div class="group-container">
          <el-form-item label="公告标题：" prop="title">
            <el-input
              v-model="addform.title"
              size="small"
              placeholder="公告标题"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
          <el-form-item label="公告标签：" prop="tag_ids">
            <el-select
              v-model="addform.tag_ids"
              multiple
              filterable
              @change="tagChange"
              placeholder="请选择"
            >
              <el-option
                :label="tag.name"
                :value="tag.id"
                v-for="tag in tagList"
                :key="tag.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="商户简称："
            prop="merchants_ids"
            v-if="userType == 1"
          >
            <el-select
              v-model="addform.merchants_ids"
              multiple
              filterable
              allow-create
              placeholder="请选择"
            >
              <el-option
                :label="user.short_name"
                :value="user.id"
                v-for="user in merchantList"
                :key="user.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="仓库简称："
            prop="warehouse_ids"
            v-if="userType == 2 || userNewType == 2"
          >
            <el-select
              v-model="addform.warehouse_ids"
              multiple
              filterable
              allow-create
              placeholder="请选择"
            >
              <el-option
                v-for="(c, index) in warehouseDictList"
                :key="index"
                :label="c.warehouse_short_name"
                :value="c.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="作者：" prop="author">
            <el-input
              v-model.trim="addform.author"
              placeholder="请输入作者"
              maxlength="10"
            />
          </el-form-item>
          <el-form-item label="排序：" prop="sort_num">
            <el-input
              v-model.trim="addform.sort_num"
              placeholder="请输入排序"
              maxlength="11"
            />
          </el-form-item>

          <el-form-item class="front" label="提示力度：" prop="prompt_type">
            <el-radio-group v-model="addform.prompt_type">
              <el-radio :label="1">不提示</el-radio>
              <el-radio :label="2">弱提示</el-radio>
              <el-radio :label="3">强提示</el-radio>
            </el-radio-group>
            <p class="dev-tips" v-if="addform.prompt_type == '3'">
              开启后每次登录弹窗展示，直到展示时间内用户阅读为止
            </p>
          </el-form-item>
          <el-form-item
            label="展示日期："
            prop="start_at"
          
          >
            <el-date-picker
              v-model.trim="addform.start_at"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            label="结束日期："
            prop="end_at"
           
          >
            <el-date-picker
              v-model.trim="addform.end_at"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="公告摘要：" prop="summary">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入小于200字的摘要"
              v-model.trim="addform.summary"
              maxlength="200"
              show-word-limit
            >
            </el-input>
          </el-form-item>
          <el-form-item label="公告详情：">
            <Tinymce ref="tinymce" :height="500" />
          </el-form-item>
        </div>
      </div>
      <div class="btn-tools">
        <el-button @click="handleSubmit()" type="primary" size="medium"
          >确认提交</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
export default {
  components: { Tinymce },
  data() {
    return {
      addform: {
        id: "",
        title: "",
        summary: "",
        tag_ids: [],
        merchants_ids: "",
        warehouse_ids: "",
        prompt_type: "",
        sort_num: "",
        content: "",
        author: "",
        start_at: "", //公告开始时间
        end_at: "", //公告下线时间
        state: "1", //状态【1：正常，0：禁止】
      },
      merchantList: JSON.parse(localStorage.getItem("merchantList")),
      userType: JSON.parse(localStorage.getItem("userType")),
      userNewType:JSON.parse(localStorage.getItem("userNewType")),
      warehouseDictList: [],
      tagList: [],
      typeform: {
        type_name: [{ name: "" }],
      },
      isEdit: false,

      classify: [],
      // 验证表单
      rules: {
        title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],

        tag_ids: [{ required: true, message: "请选择标签", trigger: "blur" }],
        merchants_ids: [
          { required: true, message: "请选择商户", trigger: "blur" },
        ],
        warehouse_ids: [
          { required: true, message: "请选择仓库", trigger: "blur" },
        ],
        author: [
          { required: true, message: "请输入作者名称", trigger: "blur" },
        ],

        sort_num: [{ required: true, message: "请输入排序", trigger: "blur" }],

        prompt_type: [
          { required: true, message: "请选择提示力度", trigger: "blur" },
        ],

        summary: [
          { required: true, message: "请输入公告详情", trigger: "blur" },
        ],
        start_at: [
          { required: true, message: "请选择展示开始时间", trigger: "blur" },
        ],
        end_at: [
          { required: true, message: "请选择展示结束时间", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.warehouseDict();
    this.noticeTagDict();
    let obj = localStorage.getItem("public");
    obj = JSON.parse(obj);
    
    if (obj) {
      this.editForm(obj)
      console.log("obj", obj.tag_id);
    }
    // console.log("obj", JSON.parse(obj));
  },
  methods: {
    editForm(obj) {
      this.addform.id = obj.id; //新建不需要传
      this.addform.title = obj.title;
      this.addform.summary = obj.summary; //
      // return
      let tagarr = obj.tag_id.split(",");
      let tagnewArr = [];
      let mArr = [];
      let wArr = [];
      tagarr.forEach((item) => {
        tagnewArr.push(+item);
      });
      if (JSON.parse(obj.merchants_ids)) {
        JSON.parse(obj.merchants_ids).forEach((item) => {
          mArr.push(+item);
        });
      }
      if (obj.warehouse_ids) {
        JSON.parse(obj.warehouse_ids).forEach((item) => {
          wArr.push(+item);
        });
      }
      this.addform.tag_ids = tagnewArr; //
      this.addform.merchants_ids = mArr; //
      this.addform.warehouse_ids = wArr; //
      this.addform.prompt_type = obj.prompt_type; //
      this.addform.sort_num = obj.sort_num; //
      this.addform.content = obj.content; //
      this.addform.author = obj.author; //
      this.addform.start_at = obj.start_at; //
      this.addform.end_at = obj.end_at; //
      //富文本
      this.$nextTick(() => {
        this.$refs.tinymce.setContent(obj.content);
      });
    },
    // 标签选择
    tagChange(e) {
      if (e.length > 5) {
        this.$message({ type: "error", message: "标签最多只能选择5条！" });
        this.addform.tag_ids.splice(-1);
      }
    },
    /**
     * 公告标签字典
     */
    async noticeTagDict() {
      const that = this;
      try {
        const { result } = await that.$.authority.noticeTagDict();
        console.log("that.typeform.type_name", result);
        console.log("result", result);
        if (result.length) {
          that.typeform.type_name = [];
          result.map((item, index) => {
            that.typeform.type_name.push({ name: "", id: "" });
            that.typeform.type_name[index].name = item.name;
            that.typeform.type_name[index].id = item.id;
          });
          console.log(
            "that.typeform.type_name",
            that.typeform.type_name,
            result
          );
          that.tagList = result;
        }
      } catch (e) {}
    },
    /**
     * 仓库列表字典
     */
    async warehouseDict() {
      const { result } = await this.$.warehouse.warehouseDict({
        warehouse_state: "1",
      });
      this.warehouseDictList = result.warehouseList;
    },

    handleSubmit(e) {
      const that = this;
      that.isEdit = false;

      that.$refs.addform.validate(async (v) => {
        if (!v) {
          return false;
        }
        // 获取富文本内容
        that.addform.content = that.$refs.tinymce.getContent();
        // console.log("富文本", that.$refs.tinymce.getContent());
        // that.addform.tag_ids = JSON.parse(that.addform.tag_ids);
        // that.addform.warehouse_ids = JSON.parse(that.addform.warehouse_ids);
        // that.addform.merchants_ids = JSON.parse(that.addform.merchants_ids);
        try {
          // that.dialogloading = true;
          // return;
          const { result } = await that.$.authority.noticeAdd(that.addform);
          that.dialogloading = false;
          that.dialogVisible = false;
          that.$message({ type: "success", message: "提交成功" });
          this.$router.push(`/authority/public`);
          that.handleSearch();
        } catch (e) {
          that.dialogloading = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.action-content {
  padding: 12px 20px;
  .group {
    margin-top: 30px;
    background-color: #fff;
    padding: 12px 20px;
    border-radius: 10px;
    .row-title {
      font-size: 15px;
      font-weight: 700;
      color: #333;
      margin-bottom: 12px;

      &::before {
        content: "";
        width: 2px;
        height: 15px;
        background-color: #1abc9c;
        display: inline-block;
        transform: translateY(-50%);
        top: 10px;
        margin-right: 5px;
        position: relative;
      }
    }
    .group-container {
      .gc-row {
        display: -webkit-flex;
        display: flex;
        align-items: center;

        .gc-row {
          margin-right: 50px;

          .gc-label {
            text-align: right;
          }
        }
      }

      .gc-label {
        min-width: 100px;
      }
    }
  }
}
</style>